<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-form-item label="上级位置" prop="parentName">
        <el-input v-model="parentName" disabled="true" />
      </el-form-item>
      <el-form-item label="位置名称" prop="name">
        <el-input v-model="formItem.name" placeholder="请输入位置名称" />
      </el-form-item>
      <el-form-item label="位置编码" prop="code">
        <el-input v-model="formItem.code" placeholder="请输入位置编码" />
      </el-form-item>
      <el-form-item label="位置顺序" prop="sort">
        <el-input v-model="formItem.sort" placeholder="请输入顺序" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  create
} from '@neu/dcam-ui/api/location'

// 定义一个表单原始项
const formItem = {
  parentId: -1,
  name: '',
  code: '',
  sort: ''
}
export default {
  name: 'DictionaryEditForm',
  props: {
    // 根据id可判断是新建还是更新
    parentId: {
      required: false,
      type: Number,
      default: null
    },
    parentName: {
      required: false,
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: {
        code: [
          { required: true, message: '位置编码不能为空', trigger: 'blur' },
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '位置名称不能为空', trigger: 'blur' },
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '顺序不能为空', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              if (/^[0-9]*$/.test(value) === false && (value + '').length <= 8) {
                callback(new Error('请输入正确的数字'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      modal: true
    }
  },
  watch: {
  },
  created() {
  },
  methods: {
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            this.formItem.parentId = this.parentId !== -1 ? this.parentId : -1
            resolve(create(this.formItem))
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    }
  }
}
</script>
